<template>
    <div class="shoppingCart">
        <div class="header">
            <van-nav-bar title="购物车" left-arrow @click-left="handleLeft">
                <template #right>
                    <div @click="clear" class="clear">清空</div>
                </template>
            </van-nav-bar>
        </div>
        <div class="screen">
            <div class="screen_div" @click="screenClicks()">
                <div class="screen_child">{{ catName }}</div>
                <van-image :src="heisexiasanjiao" class="screen_icons" />
            </div>
            <div class="screen_div" v-for="(item, index) in screenList" :key="index" @click="screenClick(index)">
                <div class="screen_child">{{ item.title }}</div>
                <div class="screen_icon">
                    <img :src="computScreen(index)" alt="" class="screen_icons">
                    <img :src="computScreens(index)" alt="" class="screen_icons">
                </div>
            </div>
        </div>
        <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
            <van-list v-model:loading="loading" :finished="finished" @load="onLoad">
                <template v-slot:finished>
                    <div class="nothing_div" v-if="warehouseList.length == 0 && !refreshing">
                        <van-image :src="icon_kongkongruye"></van-image>
                        <div class="nothing_font">购物车空空如也</div>
                    </div>
                </template>
                <van-swipe-cell v-for="(item) in warehouseList" :key="item.id">
                    <commodityList :data="item" @click="routerGo(item.type, item.id)" @deletes="deletes" />
                </van-swipe-cell>
            </van-list>
        </van-pull-refresh>
        <div class="footer" v-if="warehouseList.length">
            <van-form @submit="submit">
                <van-cell-group inset>
                    <van-field input-align="right" error-message-align="right" name="liveType" label="直播类型"
                        v-model="formData.liveType" is-link readonly placeholder="请选择" @click="showTradeMode = true"
                        required :rules="[
                            { required: true, trigger: 'onBlur', message: '请选择贸易方式' },
                        ]" />
                    <van-popup v-model:show="showTradeMode" position="bottom">
                        <van-picker :columns="tradeModeColumns" @cancel="showTradeMode = false"
                            @confirm="onConfirmTradeMode" />
                    </van-popup>
                </van-cell-group>
                <van-cell-group inset>
                    <van-field input-align="right" error-message-align="right" name="postscript" label="附言信息"
                        v-model="formData.postscript" autosize placeholder="请输入附言信息" maxlength="50" show-word-limit
                        @input="(e) => { forbidRule(e, 'emoji') }" type="textarea" />
                </van-cell-group>
                <div class="footer_button">
                    <van-button round block type="primary" native-type="submit" v-throttle:click>
                        提交({{ warehouseList.length }})
                    </van-button>
                </div>
            </van-form>
        </div>
    </div>
    <category :isShow="isShow" @leftClick="leftClick" @onSubmit="onSubmit" v-model:value="queryParams.categoryId" />
</template>
<script setup lang="ts">
import { computed, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import category from '@/components/category/index.vue'
import { getShoppingByUserId, deleteShoppingProduct, deleteShoppingAll, shoppingSubmit } from '@/api/operation/index'
import { getEnvValue } from "@/utils/index";
import commodityList from './components/cartComponent.vue'
import heiseshangsanjiao from '@/assets/productHome/icon_heiseshangsanjiao.png'
import huiseshangsanjiao from '@/assets/productHome/icon_huiseshangsanjiao.png'
import { showSuccessToast } from "vant";
const huisexiasanjiao = new URL("@/assets/productHome/icon_huisexiasanjiao.png", import.meta.url).href;
const heisexiasanjiao = new URL("@/assets/productHome/icon_heisexiasanjiao.png", import.meta.url).href;
const icon_kongkongruye = new URL("@/assets/operation/icon_kongkongruye.png", import.meta.url).href;
const router = useRouter();
const route = useRoute();
/** 楼层id */
const shelvesCode = computed(() => {
    return route.query.shelvesCode;
});
const title = computed(() => {
    return route.query.title || '';
});
const type = computed(() => {
    return route.query.type || '';
});
const url = computed(() => {
    return route.query.url || '';
});
// 商品list
const warehouseList = ref<any>([])
const showTradeMode = ref(false)
// 列表
const refreshing = ref(false);
const loading = ref(false);
const finished = ref(false);
// 限制连续刷新数据重复问题
const refreFlag = ref(true)

// rice上升 dic下降
const queryParams = ref<any>({
    groundTimeSort: '2',
    priceSort: '',
});

const formData = ref({
    postscript: '',
    liveType: ''
})

const tradeModeColumns = ref([
    { text: '平播', value: '平播' },
    { text: '打榜', value: '打榜' },
    { text: '活动', value: '活动' },
    { text: '大货', value: '大货' },
])


// 筛选集合
const screenList = ref([
    { title: '上架时间' },
])
const catName = ref('商品类目')
const isShow = ref<any>(false)
/** 商品类目 */
const screenClicks = () => {
    isShow.value = true
}
// 类目导航返回
const leftClick = () => {
    isShow.value = false
}
/** 清空 */
const clear = async () => {
    await deleteShoppingAll({ floor: title.value.includes('一') ? 1 : title.value.includes('二') ? 2 : title.value.includes('三') ? 3 : title.value.includes('四') ? 4 : title.value.includes('五') ? 5 : title.value.includes('六') ? 6 : title.value.includes('七') ? 7 : title.value.includes('八') ? 8 : title.value.includes('九') ? 9 : title.value.includes('十') ? 10 : title.value.includes('十一') ? 11 : title.value.includes('十二') ? 12 : title.value.includes('十三') ? 13 : 0 })
    warehouseList.value = []

}
// 输入事件、禁用规则
const forbidRule = (e: any, type: string) => {
    // 输入法表情默认不能输入
    if (type == 'emoji') {
        // emoji：输入时禁用输入法表情
        formData.value.postscript = e.target.value.replace(/[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[0-9|#]\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|[\u2122-\u2B55]|\u303D|[\A9|\AE]\u3030|\u00A9|\u00AE|\u3030/gi, '')
    } else if (type == 'blank') {
        // blank：输入时禁用空格
        formData.value.postscript = e.target.value.replace(/\s|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[0-9|#]\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|[\u2122-\u2B55]|\u303D|[\A9|\AE]\u3030|\u00A9|\u00AE|\u3030/gi, '')
    }
}
// 搜索查询
const onSubmit = (arr: any, tier: number) => {
    catName.value = arr[tier - 1].categoryName == '全部' ? '商品类目' : arr[tier - 1].categoryName
    isShow.value = false
    onRefresh()
}
/** 跳转详情 */
const routerGo = (type: any, id: string) => {
    if (type == 1) {
        router.push({
            path: `/researchBasicsDetail/${id}`
        })
    } else {
        router.push({
            path: `/operationBasicsDetail/${id}`
        })
    }
}
/** 筛选点击事件 */
const screenClick = (index: number) => {
    if (index == 0) {
        if (queryParams.value.groundTimeSort == '2') {
            queryParams.value.groundTimeSort = '1'
        } else {
            queryParams.value.groundTimeSort = '2'
        }
        queryParams.value.priceSort = ''
    } else if (index == 1) {
        if (queryParams.value.priceSort == '2') {
            queryParams.value.priceSort = '1'
        } else {
            queryParams.value.priceSort = '2'
        }
        queryParams.value.groundTimeSort = ''
    }
    onRefresh();
}
/** 筛选上升点击事件 */
const computScreen = (index: number) => {
    if (index == 0) {
        if (queryParams.value.groundTimeSort == '2') {
            return heiseshangsanjiao
        } else if ((queryParams.value.groundTimeSort == '1')) {
            return huiseshangsanjiao
        } else {
            return huiseshangsanjiao
        }
    } else if (index == 1) {
        if (queryParams.value.priceSort == '2') {
            return heiseshangsanjiao
        } else if (queryParams.value.priceSort == '1') {
            return huiseshangsanjiao
        } else {
            return huiseshangsanjiao
        }
    }
}
/** 筛选下降点击事件 */
const computScreens = (index: number) => {
    if (index == 0) {
        if (queryParams.value.groundTimeSort == '2') {
            return huisexiasanjiao
        } else if (queryParams.value.groundTimeSort == '1') {
            return heisexiasanjiao
        } else {
            return huisexiasanjiao
        }
    } else if (index == 1) {
        if (queryParams.value.priceSort == '2') {
            return huisexiasanjiao
        } else if (queryParams.value.priceSort == '1') {
            return heisexiasanjiao
        } else {
            return huisexiasanjiao
        }
    }
}
/** 查询商品列表 */
const getList = async () => {
    const res = await getShoppingByUserId({ ...queryParams.value, floor: title.value.includes('一') ? 1 : title.value.includes('二') ? 2 : title.value.includes('三') ? 3 : title.value.includes('四') ? 4 : title.value.includes('五') ? 5 : title.value.includes('六') ? 6 : title.value.includes('七') ? 7 : title.value.includes('八') ? 8 : title.value.includes('九') ? 9 : title.value.includes('十') ? 10 : title.value.includes('十一') ? 11 : title.value.includes('十二') ? 12 : title.value.includes('十三') ? 13 : 0 });
    res.rows.forEach(element => {
        if (element.productImage) {
            element.productImage = getEnvValue("VITE_APP_PIC_URL") + element.productImage.split(',')[0]
        }
    });

    refreFlag.value = true
    // 空数据 停止加载
    if (res.rows.length == 0) {
        warehouseList.value = [];
        finished.value = true;
        return;
    }
    // 有数据 赋值列表 加载状态结束
    res.rows.forEach((item) => {
        finished.value = false;
        warehouseList.value.push(item);
    });
    loading.value = false;
    refreshing.value = false;
    // 如果list长度大于等于总数据条数，数据全部加载完成
    if (warehouseList.value.length >= res.total) {
        finished.value = true; //结束加载
    }
};
/** 加载更多 */
const onLoad = async () => {
    getList();
    queryParams.value.pageNum++;
};
/** 下拉 */
const onRefresh = () => {
    if (refreFlag.value) {
        refreFlag.value = false
        finished.value = false; // 清空列表数据
        refreshing.value = false;
        loading.value = true; // 加载状态
        queryParams.value.pageNum = 1; // 分页数赋值为1
        warehouseList.value = []; // 清空数组
        onLoad(); // 重新加载数据
    } else {
        finished.value = false;
        refreshing.value = false;
    }
};
/** 返回 */
const handleLeft = () => {
    router.push({
        path: `/${url.value}`,
        query: {
            shelvesCode: shelvesCode.value,
            cartData: JSON.stringify(warehouseList.value)
        }
    })
}
/** 移除商品 */
const deletes = async (id: string) => {
    await deleteShoppingProduct({ id, floor: title.value.includes('一') ? 1 : title.value.includes('二') ? 2 : title.value.includes('三') ? 3 : title.value.includes('四') ? 4 : title.value.includes('五') ? 5 : title.value.includes('六') ? 6 : title.value.includes('七') ? 7 : title.value.includes('八') ? 8 : title.value.includes('九') ? 9 : title.value.includes('十') ? 10 : title.value.includes('十一') ? 11 : title.value.includes('十二') ? 12 : title.value.includes('十三') ? 13 : 0 })
    warehouseList.value = warehouseList.value.filter(item => item.id != id)
}
/** 提交商品 */
const submit = async () => {
    const productIds = warehouseList.value.map(item => item.id)
    await shoppingSubmit({ ...formData.value, productIds, type: type.value, floor: title.value.includes('一') ? 1 : title.value.includes('二') ? 2 : title.value.includes('三') ? 3 : title.value.includes('四') ? 4 : title.value.includes('五') ? 5 : title.value.includes('六') ? 6 : title.value.includes('七') ? 7 : title.value.includes('八') ? 8 : title.value.includes('九') ? 9 : title.value.includes('十') ? 10 : title.value.includes('十一') ? 11 : title.value.includes('十二') ? 12 : title.value.includes('十三') ? 13 : 0 })
    showSuccessToast('购物车提交成功')
    router.push({
        path: '/operation/operatepage',
    })
    // onRefresh()
}
const onConfirmTradeMode = ({ selectedOptions }) => {
    formData.value.liveType = selectedOptions[0].text
    showTradeMode.value = false
}
</script>
<style lang="less" scoped>
.shoppingCart {
    width: 100%;
    height: 100vh;
    display: flex;
    flex-flow: column;

    .header {
        background: linear-gradient(#CDECFF 0%, #FFFFFF 70%);
        filter: blur(0px);
        height: 90px;
        padding-top: 44px;
        box-sizing: border-box;

        :deep(.van-icon-arrow-left) {
            color: #1a1b1c !important;
        }

        :deep(.van-nav-bar) {
            background: none !important;
        }

        :deep(.van-nav-bar__content) {
            background-color: transparent !important;
        }
    }

    .clear {
        color: #0094FF;
    }

    :deep(.van-icon-arrow-left) {
        color: #000 !important;
    }

    .screen {
        display: flex;
        align-items: center;
        justify-content: space-around;
        box-sizing: border-box;
        height: 44px;
        width: 100%;
        line-height: 44px;
        background-color: #fff;
        padding: 0 20px;

        .screen_div {
            display: flex;
            align-items: center;
            display: flex;
            justify-content: center;

            .screen_icons {
                width: 10px;
                height: 6px;
                margin-left: 5px;
            }

            .screen_child {
                font-weight: 400;
                font-size: 14px;
                color: #1A1B1C;
            }

            .screen_icon {
                display: flex;
                flex-wrap: wrap;
                width: 10px;
                height: 16px;
                margin-left: 5px;

                .screen_icons {
                    width: 10px;
                    height: 6px;
                }
            }
        }
    }

    .van-pull-refresh {
        flex: 1;
        min-height: 0;
        overflow: scroll;
        background-color: #fff;
    }

    .footer {
        width: 100%;
        background: #FFFFFF;
        box-shadow: 0px 0px 8px 0px rgba(189, 195, 204, 0.5);

        .footer_button {
            padding: 0 10px 10px;
        }
    }

    .nothing_div {
        width: 100%;
        margin: auto;
        text-align: center;
        padding-top: 20vh;
        font-weight: 400;
        font-size: 12px;
        color: #B8BECA;
        line-height: 12px;
        flex-wrap: wrap;

        .van-image {
            width: 160px;
            height: 160px;
        }
    }
}
</style>